import { useSize } from "ahooks";
import { Button, GetProps, Input, Popconfirm, Table, type TableColumnsType } from "antd";
import { useEffect, useMemo, useRef, useState } from "react";
import { AddPageModal } from "./AddPageModal";
import { deletePage, getPageList } from "@/interfaces";
import { SyncOutlined } from "@ant-design/icons";
import { useComponentsStore } from "@/stores/edit-pages-store";
import { useNavigate } from "react-router-dom";
import { GFS } from "@/hooks/useAssignGlobalProps";

type SearchProps = GetProps<typeof Input.Search>;
export interface PageDataType {
  key: React.Key;
  id: number;
  label: string;
  path: string;
  icon: string;
  schema: string;
}
export default function PageManager() {
  const ref = useRef(null);
  const size = useSize(ref);
  const [dataSource, setDataSource] = useState<PageDataType[]>([]);
  const [total, setTotal] = useState(0);
  const [pageSize, setPageSize] = useState(10);
  const [current, setCurrent] = useState(1);
  const [filter, setFilter] = useState("");
  const { pages, updatePage, addPage, delPage } = useComponentsStore();
  const [openStateObj, setOpenStateObj] = useState<Record<string, boolean>>({});
  const navigate = useNavigate();

  const columns: TableColumnsType<PageDataType> = [
    {
      title: "页面名称",
      dataIndex: "label",
    },
    {
      title: "路径",
      dataIndex: "path",
    },
    {
      title: "图标",
      dataIndex: "icon",
    },
    {
      title: "操作",
      width: 120,
      align: "center",
      render: (_, record) => (
        <div>
          <Popconfirm title="删除页面" description="确认删除吗？" onConfirm={() => delCurPage(record)}>
            <Button type="text" size="small" danger>
              删除
            </Button>
          </Popconfirm>
          <Popconfirm
            title="提示"
            description="存在临时数据，需要覆盖吗？"
            open={openStateObj[record.path]}
            onOpenChange={newOpen => handleEditOpenChange(newOpen, record)}
            onConfirm={() => coverConfirm(record)}
            onCancel={() => coverCancel(record)}
            cancelText="不覆盖，跳转编辑"
            okText="覆盖"
          >
            <Button color="primary" variant="text" size="small">
              编辑
            </Button>
          </Popconfirm>
          {/* <Button color="primary" variant="text" size="small" onClick={()=>goToEdit(record)}> 编辑 </Button> */}
        </div>
      ),
    },
  ];
  async function delCurPage(record: PageDataType) {
    const {id, path} = record
    try {
      const res = await deletePage(id);

      if (res.status === 201 || res.status === 200) {
        GFS.message.success(res.data.message);
        freshPage();
        delPage(path);
      }
    } catch (e: any) {
      GFS.message.error(e.response?.data?.message || "系统繁忙，请稍后再试");
    }
  }
  function handleEditOpenChange(newOpen: boolean, record: PageDataType) {
    const { path, id } = record;
    if (!newOpen) {
      setOpenStateObj({ ...openStateObj, [path]: false });
      return;
    }
    const page = pages.find(item => item.path === path && item.id === id);
    if (!page) {
      coverCancel(record, true);
      setOpenStateObj({ ...openStateObj, [path]: false });
    } else {
      setOpenStateObj({ ...openStateObj, [path]: true });
    }
  }
  function coverConfirm(record: PageDataType) {
    const { path, schema, id } = record;
    // updatePage(path, schema);
    delPage(path)
    navigate({
      pathname: `/lowCodeEditorPlus/${path}`,
    });
    setTimeout(() => {
      setOpenStateObj({ ...openStateObj, [path]: false });
    }, 500);
  }
  //不覆盖，跳转编辑
  function coverCancel(record: PageDataType, cover: Boolean = false) {
    const { path, schema, id, icon, label } = record;
    cover && addPage(path, schema, id, icon, label);
    setOpenStateObj({ ...openStateObj, [path]: false });
    navigate({
      pathname: `/lowCodeEditorPlus/${path}`
    });
  }
  async function getData(page: number, size: number, filter: string = "") {
    const res = await getPageList(page, size, filter, "path,label");
    const { data, pager } = res.data;
    setOpenStateObj({});
    setDataSource(
      data.map((item: PageDataType) => {
        setOpenStateObj({ ...openStateObj, [item.path]: false });
        return { ...item, key: item.id };
      })
    );
    setTotal(pager.total);
  }
  useEffect(() => {
    getData(1, pageSize);
  }, []);

  function freshPage() {
    getData(current, pageSize);
  }
  const onSearch: SearchProps["onSearch"] = (value, _e, info) => {
    setFilter(value);
    getData(current, pageSize, value);
  };

  const rowH = 47; // size: 55 | 47 | 39
  const pH = 24 + 16; // pagination占用： 32 ｜ 24
  const tableHeight = useMemo(() => {
    const h = size?.height || 255;
    if (dataSource.length === 0) return undefined;
    if ((dataSource.length + 1) * rowH < h - pH) return undefined; //数据的长度加上表头高度小于容器高度就不沾湿scroll
    return columns.length > 0 ? h - rowH - pH : h - 33;
  }, [size]);
  const [isOpen, setIsOpen] = useState(false);
  return (
    <div className="flex flex-col gap-3 bg-white h-full p-4">
      <header className="flex justify-between">
        <div className="flex-1 w-10 flex gap-3">
          <Input.Search placeholder="输入页面/路径查询" onSearch={onSearch} style={{ width: 200 }} allowClear />
          <Button type="primary" onClick={() => setIsOpen(true)}>
            新增
          </Button>
        </div>
        <div>
          <Button shape="circle" icon={<SyncOutlined />} onClick={freshPage} />
        </div>
      </header>
      <main ref={ref} className="flex-1 h-20">
        <Table<PageDataType>
          size="middle"
          columns={columns}
          dataSource={dataSource}
          bordered
          pagination={{
            pageSize,
            total,
            current,
            showTotal: total => `共 ${total} 条`,
            onChange: (page, size) => {
              setCurrent(page);
              setPageSize(size);
              getData(page, size, filter);
            },
            // pageSizeOptions: [10, 20, 50, 100]
          }}
          scroll={{ y: tableHeight }}
          className={dataSource.length > 0 ? "" : "fullHeight"}
        />
      </main>
      <AddPageModal isOpen={isOpen} handleClose={() => setIsOpen(false)} freshPage={freshPage} />
    </div>
  );
}
